import { defineStore } from 'pinia'
import { useStorage } from '@vueuse/core'
// import { generatorDynamicRouter } from '@/router/generator-router'
import { ACCESS_TOKEN_KEY, USER_INFO_KEY } from '@/constants/base.contant'
// import mock from '@/mock/user'
import router from '@/router'
// import { sys_menuTree } from '@/api/menu'
// import { message } from 'ant-design-vue'

const userToken = useStorage(ACCESS_TOKEN_KEY, '')
const userInfo = useStorage(USER_INFO_KEY, {})

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: userToken.value,
    name: '',
    avatar: '',
    menus: [],
    userInfo: userInfo.value as any
  }),
  getters: {
    isAdmin(): boolean {
      return this.userInfo.loginId === 'admin'
    },
    getToken(): string {
      return this.token
    },
    getAvatar(): string {
      return this.avatar
    },
    getName(): string {
      return this.name
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token
      userToken.value = token
    },
    setUserInfo(val) {
      this.userInfo = val
      userInfo.value = val
    },
    async afterLogin() {
      this.menus = [
        {
          name: '数据统计',
          icon: 'icon-home',
          router: '/dashboard'
        },
        {
          name: '用户列表',
          icon: 'icon-user',
          router: '/user'
        },
        {
          name: '产品列表',
          icon: 'icon-repayment',
          router: '/product'
        }
      ]
      // try {
      // const [userInfo, { perms, menus }] = await Promise.all([getInfo(), permmenu()]);
      // const res = await sys_menuTree({ userId: this.userInfo.userId })
      // if (res.data.length) {
      //   this.menus = res.data
      //   // const { menus } = mock
      //   // this.menus = menus
      //   generatorDynamicRouter(this.menus)
      // } else {
      //   message.error('当前职位没有配置菜单权限，请联系管理员')
      //   this.logout()
      // }
      // } catch (error) {
      //   return this.logout()
      // }
    },
    // 退出登录
    async logout() {
      this.token = ''
      this.userInfo = {}
      userToken.value = null
      userInfo.value = null
      router.replace(`/login?redirect=${router.currentRoute.value.fullPath}`)
    }
  }
})
